package com.ruicar.afs.cloud.apply.archive.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.apply.archive.condition.ImageCondition;
import com.ruicar.afs.cloud.apply.archive.condition.MoreProducttCondition;
import com.ruicar.afs.cloud.apply.archive.service.MoreProductService;
import com.ruicar.afs.cloud.apply.archive.service.WaybillService;
import com.ruicar.afs.cloud.archive.dto.ImageDto;
import com.ruicar.afs.cloud.archive.dto.MoreProducttDto;
import com.ruicar.afs.cloud.archive.dto.PostDto;
import com.ruicar.afs.cloud.archive.feign.ArchiveApiFeign;
import com.ruicar.afs.cloud.archive.result.ArchiveCommon.ArchivedPicture;
import com.ruicar.afs.cloud.archive.result.ArchiveDocListDto.ArchivedDocEdit;
import com.ruicar.afs.cloud.archive.result.ArchivePostDetailDto.ArchivedDcPostDetail;
import com.ruicar.afs.cloud.archive.result.ArchivePostDetailDto.ArchivedPostDetailInfo;
import com.ruicar.afs.cloud.archive.result.ArchivePostListDto.ArchivedPostDetail;
import com.ruicar.afs.cloud.archive.result.ArchivedPageDto;
import com.ruicar.afs.cloud.archive.result.ArchivedResultDto;
import com.ruicar.afs.cloud.archive.service.ArchiveService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 多品接口
 * @author: yaorui.zhang
 * @date: 2020年8月4日 14:36:56
 */
@Service
@AllArgsConstructor
@Slf4j
public class MoreProductServiceImpl implements MoreProductService {

    private ArchiveApiFeign archiveApiFeign;
    private WaybillService waybillService;
    private ArchiveService archiveService;

    /**
     * 获取token信息
     *
     * @return
     */
    public String getAuthorization() {
        String authorization = archiveService.getAuthorization();
        return authorization;
    }

    /**
     * 多品归档编辑和查看页面
     * @param condition
     * @return
     */
    public IResponse editview(MoreProducttCondition condition) {

        MoreProducttDto dto = new MoreProducttDto();
        dto.setCacontractId(condition.getCacontractId());
        dto.setIsEdit(condition.getIsEdit());
        dto.setIsNotPost(condition.getIsNotPost());

        PostDto postDto = new PostDto();
        postDto.setApplicationNo(condition.getApplicationNo()); //类型：String  必有字段  备注：申请编号（前端用）
        postDto.setDcpostId(condition.getDcpostId()); //类型：String  必有字段  备注： 提交归档信息DCPOST邮寄信息表id对应前台原postfile.dcpostid （前端用）

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            ArchivedResultDto jsonCheck =  archiveApiFeign.checkPostDoc(postDto, headers);
            if(1== jsonCheck.getSuccess()){
                dto.setIsEdit(false);//默认查看
                if("1".equals(jsonCheck.getData().toString())){
                    dto.setIsNotPost(true);
                }else{
                    dto.setIsNotPost(false);
                }
                ArchivedResultDto archivedResultDto = archiveApiFeign.editview(dto, headers);
                if(1==archivedResultDto.getSuccess()){
                    ArchivedDocEdit archivedDocEdit = JSON.parseObject(JSON.toJSONString(archivedResultDto.getData()), ArchivedDocEdit.class);
                    List<ArchivedPicture> impictureMd5List = new ArrayList();
                    List<ArchivedPicture> archivedDocEditPictureList = archivedDocEdit.getPictureList();
                    BASE64Encoder encoder = new BASE64Encoder();
                    for(ArchivedPicture archivedPicture : archivedDocEditPictureList){
                        ImageCondition imageCondition = new ImageCondition();
                        imageCondition.setMd5(archivedPicture.getMd5());
                        byte[] md5 = waybillService.downFile(imageCondition);
                        archivedPicture.setMd5Byte(encoder.encode(md5));
                        impictureMd5List.add(archivedPicture);
                    }
                    archivedDocEdit.setMd5List(impictureMd5List);
                    return IResponse.success(archivedDocEdit);
                }else{
                    return IResponse.fail(archivedResultDto.getMessage());
                }
            }else{
                return IResponse.fail(jsonCheck.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 多品获取邮单列表
     * @param condition
     * @return
     */
    public IResponse getlist(MoreProducttCondition condition) {

        MoreProducttDto dto = new MoreProducttDto();
        dto.setPostNo(condition.getPostNo());
        dto.setPageIndex(condition.getPageIndex());
        dto.setPageSize(condition.getPageSize());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            ArchivedResultDto json =  archiveApiFeign.getlist(dto, headers);
            if(1==json.getSuccess()){
                ArchivedPageDto archivedPageDto = JSON.parseObject(JSON.toJSONString(json.getData()), ArchivedPageDto.class);
                List<ArchivedPostDetail> list = JSON.parseArray(JSON.toJSONString(archivedPageDto.getData()), ArchivedPostDetail.class);
                //分页处理
                IPage iPage = new Page();
                iPage.setRecords(list);
                iPage.setPages(archivedPageDto.getPageIndex());
                iPage.setSize(archivedPageDto.getPageSize());
                iPage.setTotal(archivedPageDto.getRecordsTotal());
                return IResponse.success(iPage);
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 多品获取邮单详情
     * @return
     */
    public IResponse getdetail(MoreProducttCondition condition) {

        MoreProducttDto dto = new MoreProducttDto();
        dto.setPostNo(condition.getPostNo());
        dto.setPageIndex(condition.getPageIndex());
        dto.setPageSize(condition.getPageSize());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            ArchivedResultDto lastPost =  archiveApiFeign.getLastPost(headers);
            ArchivedPostDetail archivedPostDetail = JSON.parseObject(JSON.toJSONString(lastPost.getData()), ArchivedPostDetail.class);
            dto.setDcPostId(archivedPostDetail.getDcPostId());
            ArchivedResultDto json =  archiveApiFeign.getdetail(dto, headers);
            if(1==json.getSuccess()){
                ArchivedPostDetailInfo archivedPageDto = JSON.parseObject(JSON.toJSONString(json.getData()), ArchivedPostDetailInfo.class);
                List<ArchivedDcPostDetail> list = JSON.parseArray(JSON.toJSONString(archivedPageDto.getDcPostDetail().getData()), ArchivedDcPostDetail.class);
                //结果分页
                List<ArchivedDcPostDetail> result = new ArrayList();
                //客户给出的list结果
                for(ArchivedDcPostDetail archivedDcPostDetail : list){
                    String impictureMd5 = archivedDcPostDetail.getImpictureMd5();
                    List impictureMd5List = new ArrayList();
                    if(StringUtils.isNotEmpty(impictureMd5)){
                        String[] split = impictureMd5.split(",");
                        BASE64Encoder encoder = new BASE64Encoder();
                        for (int i = 0; i < split.length; i++) {
                            ImageCondition imageCondition = new ImageCondition();
                            imageCondition.setMd5(split[i]);
                            byte[] md5 = waybillService.downFile(imageCondition);
                            impictureMd5List.add( encoder.encode(md5));
                        }
                    }
                    archivedDcPostDetail.setMd5List(impictureMd5List);
                    result.add(archivedDcPostDetail);
                }

                IPage iPage = new Page();
                iPage.setRecords(result);
                iPage.setPages(archivedPageDto.getDcPostDetail().getPageIndex());
                iPage.setSize(archivedPageDto.getDcPostDetail().getPageSize());
                iPage.setTotal(archivedPageDto.getDcPostDetail().getRecordsTotal());

                List<ArchivedPostDetail> dcPost = JSON.parseArray(JSON.toJSONString(archivedPageDto.getDcPost().getData()), ArchivedPostDetail.class);

                JSONObject jsonReturn = new JSONObject();
                jsonReturn.put("dcPost",dcPost);
                jsonReturn.put("dcPostDetail",iPage);

                return IResponse.success(jsonReturn);
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 档案系统用到的各种数据字典的接口
     * @param condition
     * @return
     */
    public IResponse getcodes(MoreProducttCondition condition) {

        MoreProducttDto dto = new MoreProducttDto();
        dto.setTypeId(condition.getTypeId());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            ArchivedResultDto json =  archiveApiFeign.getcodes(dto, headers);
            if(1==json.getSuccess()){
                return IResponse.success(json.getData());
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }


    /**
     * 从fms库删除影像件
     * @param condition
     * @return
     */
    public IResponse delImageFormFms(ImageCondition condition) {

        JSONObject dto = new JSONObject();
        dto.put("RandomStr",condition.getRandomStr());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            JSONObject json =  archiveApiFeign.delImageFormFms(dto, headers);
            if("1".equals(json.get("success").toString())){
                return IResponse.success(json.get("data"));
            }else{
                return IResponse.fail(json.get("message").toString());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }


    /**
     * 影像件上次后保存业务数据
     * @param condition
     * @return
     */
    public IResponse dcsaveinfo(ImageCondition condition) {

        ImageDto dto = new ImageDto();
        dto.setName(condition.getName());//类型：String  必有字段  备注：文件名称
        dto.setStatus(condition.getStatus());//类型：Number  必有字段  备注：提交状态
        dto.setMd5(condition.getMd5()); //类型：String  必有字段  备注：Md5
        dto.setRandomStr(condition.getRandomStr());//类型：String  必有字段  备注：唯一随机串
        dto.setOldRandomStr(condition.getOldRandomStr());//类型：String  必有字段  备注：旧的唯一随机串
        dto.setImCategoryCode(condition.getImCategoryCode());//类型：String  必有字段  备注：文件类型
        dto.setCamainId(condition.getCamainId()); //类型：String  必有字段  备注：案件id
        dto.setCUser(condition.getCUser()); //类型：String  必有字段  备注：创建人
        dto.setScene(condition.getScene()); //类型：Number  必有字段  备注：场景
        dto.setIsCap(condition.getIsCap()); //类型：Number  必有字段  备注：是否高拍仪
        dto.setUploadFrom(condition.getUploadFrom());//类型：Number  必有字段  备注：图片途径
        dto.setMidId(condition.getMidId());//类型：String  必有字段  备注：中间件标识
        dto.setSize(condition.getSize());//类型：Number  必有字段  备注：文件大小
        dto.setSuccess(condition.getSuccess()); //类型：String  必有字段  备注：上传成功标志

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            ArchivedResultDto json =  archiveApiFeign.dcsaveinfo(dto, headers);
            if(1==json.getSuccess()){
                return IResponse.success(json.getData());
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

}
